<template>
  <div class="settlement">
    <van-nav-bar
      title="下班结算"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 今日概览 -->
    <div class="daily-overview">
      <div class="overview-item">
        <span class="label">营业总额</span>
        <span class="value income">¥{{ dailyTotal }}</span>
      </div>
      <div class="overview-item">
        <span class="label">订单数量</span>
        <span class="value">{{ orderCount }}笔</span>
      </div>
      <div class="overview-item">
        <span class="label">客户数量</span>
        <span class="value">{{ customerCount }}人</span>
      </div>
    </div>

    <!-- 未完成订单 -->
    <div class="pending-orders">
      <div class="section-header">
        <div class="title">
          <van-badge :content="pendingOrders.length" :max="99">
            <span>未完成订单</span>
          </van-badge>
        </div>
        <div class="actions">
          <van-button size="small" type="primary" @click="generateAllBills" :disabled="pendingOrders.length === 0">
            批量生成账单
          </van-button>
        </div>
      </div>
      
      <div class="orders-list" v-if="pendingOrders.length > 0">
        <div v-for="order in pendingOrders" :key="order.id" class="order-item">
          <div class="customer-info">
            <img :src="order.customerAvatar" alt="avatar" class="avatar">
            <div class="info">
              <div class="name">{{ order.customerName }}</div>
              <div class="time">{{ order.time }}</div>
            </div>
          </div>
          <div class="order-summary">
            <div class="products">
              <span v-for="(product, index) in order.products.slice(0, 2)" :key="product.id">
                {{ product.name }}{{ index < Math.min(order.products.length - 1, 1) ? '、' : '' }}
              </span>
              <span v-if="order.products.length > 2">等{{ order.products.length }}件</span>
            </div>
            <div class="amount">¥{{ order.totalAmount.toFixed(2) }}</div>
          </div>
          <div class="order-actions">
            <van-button size="small" type="primary" @click="generateOrderBill(order)">生成账单</van-button>
          </div>
        </div>
      </div>
      
      <div class="empty-list" v-else>
        <van-empty description="暂无未完成订单" />
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'

// 定义类型
interface Product {
  id: number;
  name: string;
  quantity: number;
  price: number;
  originalPrice?: number;
}

interface Order {
  id: number;
  customerId: number;
  customerName: string;
  customerAvatar: string;
  date: string;
  time: string;
  products: Product[];
  totalAmount: number;
  status: 'pending' | 'completed';
  priceAdjustments?: {
    productId: number;
    productName: string;
    originalPrice: number;
    newPrice: number;
    quantity: number;
    difference: number;
  }[];
}

const route = useRoute()
const router = useRouter()

// 今日数据
const dailyTotal = ref(2580.50)
const orderCount = ref(45)
const customerCount = ref(28)

// 排行选项
const rankingOptions = [
  { text: '销量排行', value: 0 },
  { text: '金额排行', value: 1 }
]

// 排行数据
const rankingList = ref([
  { id: 1, name: '康师傅红烧牛肉面', count: 35 },
  { id: 2, name: '统一老坛酸菜面', count: 28 },
  { id: 3, name: '雪碧', count: 20 },
  { id: 4, name: '可口可乐', count: 18 },
  { id: 5, name: '农夫山泉', count: 15 }
])

// 未完成订单
const pendingOrders = ref<Order[]>([
  {
    id: 101,
    customerId: 1,
    customerName: '张大姐',
    customerAvatar: '/avatars/1.png',
    date: '2024-01-20',
    time: '14:30',
    products: [
      { id: 1, name: '康师傅红烧牛肉面', quantity: 2, price: 4.5 },
      { id: 2, name: '统一老坛酸菜面', quantity: 1, price: 4.0 },
      { id: 3, name: '雪碧', quantity: 1, price: 3.0 }
    ],
    totalAmount: 16.0,
    status: 'pending'
  },
  {
    id: 102,
    customerId: 2,
    customerName: '老刘',
    customerAvatar: '/avatars/2.png',
    date: '2024-01-20',
    time: '16:45',
    products: [
      { id: 4, name: '可口可乐', quantity: 2, price: 3.0 },
      { id: 5, name: '矿泉水', quantity: 1, price: 2.0 }
    ],
    totalAmount: 8.0,
    status: 'pending'
  },
  {
    id: 103,
    customerId: 3,
    customerName: '王师傅',
    customerAvatar: '/avatars/3.png',
    date: '2024-01-20',
    time: '17:20',
    products: [
      { id: 6, name: '香辣方便面', quantity: 3, price: 4.0 }
    ],
    totalAmount: 12.0,
    status: 'pending'
  }
])

// 格式化日期
const formatDate = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生成单个订单账单
const generateOrderBill = (order: Order) => {
  const toast = showToast({
    type: 'loading',
    message: '正在生成账单...',
    forbidClick: true,
    duration: 0
  })
  
  setTimeout(() => {
    toast.close()
    router.push(`/bill-preview/${order.id}`)
  }, 1000)
}

// 批量生成所有未完成订单的账单
const generateAllBills = () => {
  const toast = showToast({
    type: 'loading',
    message: '正在生成批量账单...',
    forbidClick: true,
    duration: 0
  })
  
  setTimeout(() => {
    toast.close()
    router.push('/batch-bill-preview')
  }, 1000)
}

// 处理从BatchBillPreview返回的已完成订单
onMounted(() => {
  const { completed, timestamp } = route.query
  
  if (completed && timestamp) {
    try {
      const completedOrderIds = JSON.parse(completed as string)
      
      if (Array.isArray(completedOrderIds) && completedOrderIds.length > 0) {
        // 移除已完成的订单
        pendingOrders.value = pendingOrders.value.filter(
          order => !completedOrderIds.includes(order.id)
        )
        
        // 显示成功消息
        showToast({
          type: 'success',
          message: `${completedOrderIds.length}个订单已完成`,
          duration: 2000
        })
        
        // 清除URL参数，防止刷新页面重复处理
        router.replace({ path: '/settlement' })
      }
    } catch (error) {
      console.error('解析完成订单数据失败', error)
    }
  }
})

onMounted(() => {
  // 初始化页面数据
})
</script>

<style lang="scss" scoped>
.settlement {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  overflow-y: auto;

  .daily-overview {
    background: #fff;
    padding: 20px;
    margin: 15px 15px 10px;
    border-radius: 12px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .overview-item {
      text-align: center;

      .label {
        color: #666;
        font-size: 14px;
        margin-bottom: 8px;
        display: block;
      }

      .value {
        font-size: 20px;
        font-weight: bold;
        color: #323233;

        &.income {
          color: #07c160;
        }
      }
    }
  }

  .pending-orders, 
  .sales-ranking {
    background: #fff;
    margin: 10px 15px;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .title {
      font-size: 16px;
      font-weight: bold;
      display: flex;
      align-items: center;
    }

    .actions {
      display: flex;
      gap: 10px;
    }
  }

  .orders-list {
    .order-item {
      background: #f9f9f9;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 10px;

      .customer-info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .avatar {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          margin-right: 10px;
          object-fit: cover;
        }

        .info {
          flex: 1;

          .name {
            font-size: 15px;
            font-weight: 500;
            margin-bottom: 2px;
          }

          .time {
            font-size: 12px;
            color: #999;
          }
        }
      }

      .order-summary {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        font-size: 14px;

        .products {
          color: #666;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .amount {
          font-weight: bold;
          color: #ee0a24;
        }
      }

      .order-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
      }
    }
  }

  .empty-list {
    padding: 20px 0;
    text-align: center;
  }

  .ranking-list {
    .ranking-item {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .rank-number {
        width: 24px;
        height: 24px;
        background: #f5f5f5;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        font-size: 14px;
        color: #666;

        &.top-three {
          background: #ffd700;
          color: #fff;
        }
      }

      .item-info {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .name {
          font-size: 14px;
        }

        .count {
          color: #ee0a24;
          font-weight: bold;
        }
      }
    }
  }

  .settlement-actions {
    padding: 20px;
    margin-top: auto;

    .action-btn {
      height: 44px;
      font-size: 16px;
    }
  }

  .order-detail {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 20px;

    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 18px;
      }
    }

    .customer-card {
      display: flex;
      align-items: center;
      background: #f9f9f9;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;

      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-right: 12px;
        object-fit: cover;
      }

      .info {
        .name {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 4px;
        }

        .time {
          font-size: 13px;
          color: #999;
        }
      }
    }

    .product-list {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;

      .product-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #f5f5f5;

        .product-info {
          .product-name {
            font-size: 15px;
            margin-bottom: 4px;
          }

          .product-quantity {
            font-size: 13px;
            color: #999;
          }
        }

        .product-price-section {
          .product-price {
            font-size: 15px;
            font-weight: 500;
          }
        }
      }
    }

    .detail-footer {
      border-top: 1px solid #eee;
      padding-top: 15px;

      .total {
        text-align: right;
        font-size: 16px;
        margin-bottom: 15px;

        span {
          font-weight: bold;
          color: #ee0a24;
        }
      }
    }
  }

  .bill-preview-popup {
    width: 90%;
    max-width: 360px;
    max-height: 90%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    position: fixed;
    margin: 0;
  }

  .bill-preview {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 20px;
    box-sizing: border-box;

    .preview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: bold;
      }
    }

    .preview-content {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;
      
      .date-info {
        text-align: center;
        color: #666;
        font-size: 14px;
        margin-bottom: 20px;
      }

      .customer-info {
        margin-bottom: 20px;
        padding: 15px;
        background-color: #f9f9f9;
        border-radius: 8px;
        font-size: 14px;

        .customer-name, .order-time {
          margin-bottom: 8px;
        }
      }

      .order-products {
        margin-bottom: 20px;

        .products-header {
          display: grid;
          grid-template-columns: 2fr 1fr 1fr;
          font-weight: 500;
          font-size: 14px;
          padding-bottom: 10px;
          border-bottom: 1px solid #eee;
        }

        .product-row {
          display: grid;
          grid-template-columns: 2fr 1fr 1fr;
          font-size: 14px;
          padding: 12px 0;
          border-bottom: 1px dashed #f5f5f5;

          .product-price {
            text-align: right;
            font-weight: 500;
          }
        }

        .total-row {
          display: grid;
          grid-template-columns: 2fr 1fr 1fr;
          font-weight: 500;
          font-size: 16px;
          padding-top: 15px;
          margin-top: 5px;

          .total-price {
            text-align: right;
            color: #ee0a24;
            font-weight: bold;
          }
        }
      }

      .batch-summary {
        .preview-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 15px;
          font-size: 15px;

          .value {
            font-weight: 500;
          }
        }

        .orders-list {
          margin-top: 15px;
          background-color: #f9f9f9;
          border-radius: 8px;
          padding: 12px;

          .order-summary-row {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            padding: 8px 0;
            border-bottom: 1px dashed #eee;
            
            &:last-child {
              border-bottom: none;
            }
          }
        }
      }

      .divider {
        height: 1px;
        background-color: #eee;
        margin: 15px 0;
      }

      .signature-area {
        margin-top: 40px;

        .signature-line {
          display: flex;
          font-size: 14px;

          .line {
            flex: 1;
            margin-left: 10px;
            color: #ccc;
          }
        }
      }
    }
    
    .preview-footer {
      padding-top: 15px;
      border-top: 1px solid #eee;
    }
  }

  .clear-confirm-content {
    padding: 20px;
    text-align: center;

    p {
      margin: 0 0 10px;
    }

    .warning {
      color: #ee0a24;
      font-size: 14px;
    }
  }
}

// 价格编辑器样式
.price-editor {
  padding: 16px;
  
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      font-size: 18px;
      font-weight: 500;
      margin: 0;
    }
  }
  
  .product-info {
    margin-bottom: 20px;
    background: #f7f8fa;
    padding: 12px;
    border-radius: 8px;
    
    .product-name {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 8px;
    }
    
    .current-price, .quantity-info, .total-price {
      display: flex;
      justify-content: space-between;
      margin-bottom: 4px;
      font-size: 14px;
      
      .price-value {
        font-weight: 500;
      }
    }
  }
  
  .price-summary {
    margin-top: 20px;
    background: #f7f8fa;
    padding: 12px;
    border-radius: 8px;
    
    .new-total, .price-difference {
      display: flex;
      justify-content: space-between;
      margin-bottom: 4px;
      font-size: 14px;
      
      .price-value {
        font-weight: 500;
      }
    }
    
    .price-increase {
      color: #07c160;
      font-weight: 500;
    }
    
    .price-decrease {
      color: #ee0a24;
      font-weight: 500;
    }
  }
  
  .editor-actions {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}

// 商品价格区域
.product-price-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

// 订单详情商品项样式
.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

// 账单样式
.adjustments-section {
  margin-top: 20px;
  
  .section-title {
    font-weight: 500;
    margin-bottom: 8px;
  }
  
  .adjustment-row {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    margin-bottom: 6px;
  }
  
  .adjustment-total, .final-total {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid #ebedf0;
  }
  
  .price-increase {
    color: #07c160;
  }
  
  .price-decrease {
    color: #ee0a24;
  }
}

.order-detail-popup {
  width: 90%;
  max-width: 360px;
  max-height: 90%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  margin: 0;
}

.bill-preview-popup {
  width: 90%;
  max-width: 360px;
  max-height: 90%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  margin: 0;
}

.price-editor-popup {
  width: 90%;
  max-width: 360px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  margin: 0;
}
</style> 